import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import App from 'layout/App.js'
import './index.less';
import { Icon, Table, Pagination, FormControl, Button, Popconfirm, Breadcrumb, Modal, FormGroup, Label } from 'tinper-bee';
import { searchCatalog, deleteCatalog, copyCatalog } from './workdatacata.config'
import { vendorsDanger as danger, vendorsSuccess as success, vendorsFmtDate as fmtDate, vendorsTrimStr as trimStr } from 'utils/config.js';
import CommonModal from './../../components/CommonModal/index.jsx';
import PresetTemplate from './../../components/PresetTemplate/index.jsx';

export default class WorkDataCata extends Component {
    constructor(props) {
        super(props);

        this.state = {
            data: [],
            activePage: 1,
            items: 1,
            searchText: '',
            showModal: false,
            newcataname: ''
        };
    }

    getListData = (condition, start, size = 10) => {
        let _me = this;

        searchCatalog({ 'isAjax': 1, ieStamp: new Date().getTime(), 'condition': condition, 'start': start, 'size': size })
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    let data = response.data.result.objects;
                    let pages = Math.ceil(response.data.result.count / 10);

                    data.forEach((cur, index) => {
                        cur.key = cur.pkCompletedCatalog;
                        let temp = (index + 1).toString();
                        temp = temp.length < 2 ? 0 + temp : temp;
                        cur.number = temp;
                        cur.creationtime = fmtDate(cur.creationtime);
                    });

                    _me.setState({
                        data: data,
                        items: pages,
                        showModal: false
                    });

                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }

    componentDidMount = () => {
        let _me = this;

        sessionStorage.removeItem('editcata');
        this.getListData(this.state.searchText, this.state.activePage);
    }


    handleSearchClick = (e) => {
        if (e.charCode && e.charCode != 13) return;

        let st = trimStr(this.state.searchText);

        this.setState({
            searchText: st
        });

        this.getListData(st, 1);

    }

    handleSelect = (e) => {
        this.setState({
            activePage: e
        });
        this.getListData(this.state.searchText, e);

    }

    handleSearchChange = (e) => {
        this.setState({ searchText: e.target.value });
    }

    deleteRow = (text, e) => {
        console.log('删除行');
        let _me = this;
        let catalogVO = this.state.data.filter(cur => cur.pkCompletedCatalog == text)[0];

        deleteCatalog({ 'isAjax': 1, ieStamp: new Date().getTime(), pkCompletedCatalog: text, changeFlag: catalogVO.changeFlag })
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    if (_me.state.data.length <= 1) {
                        _me.state.activePage = (_me.state.activePage - 1) || 1;

                        // _me.setState({
                        //     activePage:(_me.state.activePage-1)||1
                        // });
                    }
                    _me.getListData(_me.state.searchText, _me.state.activePage);
                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }

    addCatalog = () => {
        sessionStorage.setItem("editcata", "");
        window.location.href = "./workdatabuild.html";
    }

    editRow = (record, e) => {
        console.log('编辑行');
        sessionStorage.setItem("editcata", record.pkCompletedCatalog);
        window.location.href = "./workdatabuild.html";
    }

    copyRow = (record, e) => {
        console.log('复制行');
        this.setState({
            showModal: true
        });
        this.pkCompletedCatalog = record.pkCompletedCatalog;
    }

    showDetail = (record, e) => {
        console.log('查看行');
        sessionStorage.setItem("editcata", record.pkCompletedCatalog);
        window.location.href = "./workdatacatadetail.html";
    }

    handleNewNameChange = (e) => {
        this.setState({ newcataname: e.target.value.substr(0, 50) });
    }

    close = () => {
        this.setState({
            showModal: false,
            modaltoCommit: false
        })
    }

    submith = () => {
        let copyName = trimStr(this.state.newcataname);

        if (copyName.length <= 0) {
            this.setState({
                newcataname: copyName,
                modaltoCommit: true
            });
            return;
        }

        let _me = this;
        copyCatalog({ 'isAjax': 1, ieStamp: new Date().getTime(), pkCompletedCatalog: this.pkCompletedCatalog, copyName })
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    _me.getListData(_me.state.searchText, _me.state.activePage);
                    success({ 'text': '复制成功！' });
                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }


    render() {
        let _me = this;
        const columns6 = [
            { title: "序号", dataIndex: "number", key: "a", width: '4%' },
            {
                title: "目录名称", dataIndex: "sname", key: "b", width: 200,
                render(text, record, index) {

                    return (
                        <div className="hrowop">
                            <span onClick={_me.showDetail.bind(null, record)}>{text}</span>
                        </div>
                    );
                }
            },
            { title: "类型", dataIndex: "catalogType", key: "c", width: 200 },
            { title: "创建人", dataIndex: "creatorName", key: "d", width: '6%' },
            { title: "创建日期", dataIndex: "creationtime", key: "e", width: '7%' },
            {
                title: "操作", dataIndex: "pkCompletedCatalog", key: "f",
                render(text, record, index) {

                    return (
                        <div className="hrowop">
                            <span onClick={_me.editRow.bind(null, record)}>编辑  </span>|
                            <span onClick={_me.copyRow.bind(null, record)}>  复制  </span>|
                            <Popconfirm trigger="click" placement="top" content={<div className="table-delete clearfix">
                                <i className="uf uf-exc-c hdelwarning"></i>
                                <span className="hdelspan">你确定删除该目录吗？</span>
                            </div>} onClose={_me.deleteRow.bind(null, text)} rootClose={true}>
                                <span>  删除</span>
                            </Popconfirm>
                        </div>
                    );
                }, width: '11%'
            }
        ];

        let newNameToFill = this.state.modaltoCommit && (!this.state.newcataname);

        return (
            <App>
                <div className="hhead">
                    <Breadcrumb className="hheadcrumb">
                        <Breadcrumb.Item active>
                            目录列表
                        </Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <div className="hbodyone">
                    <div className="hbodyopecata">
                        <div className="hbodyopeleft">
                            目录名称：
            <FormControl value={this.state.searchText} className="hsearch" placeholder="请输入目录名称、类型" onChange={this.handleSearchChange} onKeyPress={this.handleSearchClick} />
                            <div className="hsearchbtn" onClick={this.handleSearchClick}>
                                <Icon type="uf-search-light-2"></Icon>
                            </div>
                        </div>
                        <div className="hbodyoperight">
                            <Button className="hadd" colors="primary" onClick={this.addCatalog}>创建目录</Button>
                        </div>
                    </div>
                    <Table columns={columns6} data={this.state.data} useFixedHeader={true} emptyText={() => '暂无数据'} />
                    <div>
                        <Pagination style={{ float: 'right', margin: '5px 0' }}
                            first
                            last
                            prev
                            next
                            boundaryLinks
                            items={this.state.items}
                            maxButtons={5}
                            activePage={this.state.activePage}
                            onSelect={this.handleSelect}
                        />
                        <div style={{ height: '35px' }}></div>
                    </div>
                </div>
                <Modal
                    className='hcreatemodal'
                    show={this.state.showModal}
                    onHide={this.close}
                    style={{ width: 450, top: 100 }}
                    backdrop={false}
                >
                    <Modal.Header className='hmodalheader' closeButton={true}>
                        复制目录
                    </Modal.Header>

                    <Modal.Body>
                        <div style={{ width: 400, margin: '0 auto', paddingLeft: 20 }}>
                            <FormGroup>
                                <Label>目录名称</Label>
                                <FormControl className={newNameToFill ? 'hmodalinput hinputrequired' : 'hmodalinput'}
                                    value={this.state.newcataname}
                                    onChange={this.handleNewNameChange}
                                />
                            </FormGroup>
                            <div style={{ visibility: newNameToFill ? "visible" : "hidden" }}><span className="hrequired">请输入目录名称</span></div>
                        </div>
                    </Modal.Body>

                    <Modal.Footer className="text-center">
                        <Button bordered style={{ marginRight: 20 }} onClick={this.close}>
                            取消
                        </Button>
                        <Button colors="primary" onClick={this.submith}>
                            确认
                        </Button>
                    </Modal.Footer>
                </Modal>
            </App>
        );
    }
}